using System;
using System.Collections.Generic;
using System.Text;

namespace Avanzis.Helpers.PersistentObjects
{
    /// <summary>
    /// Implementation of <see cref="ISessionScope"/> to 
    /// augment performance by caching the session, thus
    /// avoiding too much opens/flushes/closes.
    /// </summary>
    public class SessionScope : AbstractScope
    {
        protected SessionScope(FlushAction flushAction, SessionScopeType type)
            : base(flushAction, type)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        public SessionScope()
            : this(FlushAction.Auto)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="flushAction"></param>
        public SessionScope(FlushAction flushAction)
            : base(flushAction, SessionScopeType.Simple)
        {
        }

        public void Dispose(bool discardChanges)
        {
            ThreadScopeAccessor.Instance.UnRegisterScope(this);

            PerformDisposal(key2Session.Values, !discardChanges, true);

            key2Session.Clear();
            key2Session = null;
        }

        protected override void PerformDisposal(IList<Session> sessions)
        {
            if (FlushAction == FlushAction.Never)
            {
                PerformDisposal(sessions, false, true);
            }
            else if (FlushAction == FlushAction.Auto)
            {
                PerformDisposal(sessions, true, true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static ISessionScope Current
        {
            get
            {
                if (ThreadScopeAccessor.Instance.HasInitializedScope)
                {
                    return ThreadScopeAccessor.Instance.GetRegisteredScope();
                }

                return null;
            }
        }
    }
}
